<script setup>
import { ref, computed, watch } from 'vue'
//import { ElDialog } from 'element-plus';

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true
  },
  // 表格列定义
  columns: {
    type: Array,
    required: true
  },
  // 是否显示分页
  pagination: {
    type: Boolean,
    default: true
  },
  // 每页条数选项
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  // 默认每页条数
  defaultPageSize: {
    type: Number,
    default: 10
  },
  // 是否允许列显示控制
  columnControl: {
    type: Boolean,
    default: true
  },
  // 是否允许编辑
  editable: {
    type: Boolean,
    default: true
  },
  // 标识字段名
  rowKey: {
    type: String,
    default: 'id'
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'page-change',
  'size-change', 
  'sort-change', 
  'row-add', 
  'row-edit', 
  'row-delete',
  'selection-change'
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(props.defaultPageSize)
const total = computed(() => props.data.length)

// 排序相关
const sortColumn = ref('')
const sortDirection = ref('')

// 列控制相关
const visibleColumns = ref([...props.columns.map(col => col.prop)])
const controlVisible = ref(false)

// 编辑相关
const editingRow = ref(null)
const editingForm = ref({})
const addFormVisible = ref(false)
const addForm = ref({})

// 过滤和排序后的数据
const processedData = computed(() => {
  let result = [...props.data]

  // 应用排序
  if (sortColumn.value && sortDirection.value) {
    result.sort((a, b) => {
      const valueA = a[sortColumn.value]
      const valueB = b[sortColumn.value]
      
      if (sortDirection.value === 'ascending') {
        return valueA > valueB ? 1 : -1
      } else {
        return valueA < valueB ? 1 : -1
      }
    })
  }

  return result
})

// 当前页的数据
const currentPageData = computed(() => {
  if (!props.pagination) return processedData.value
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return processedData.value.slice(start, end)
})

// 分页变化
const handlePageChange = (val) => {
  currentPage.value = val
  emit('page-change', { page: val, size: pageSize.value })
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  emit('size-change', val)
}

// 排序变化
const handleSortChange = ({ column, prop, order }) => {
  sortColumn.value = prop
  sortDirection.value = order
  emit('sort-change', { column, prop, order })
}

// 选择列显示/隐藏
const toggleColumnVisibility = (prop) => {
  const index = visibleColumns.value.indexOf(prop)
  if (index !== -1) {
    visibleColumns.value.splice(index, 1)
  } else {
    visibleColumns.value.push(prop)
  }
}

// 开始编辑行
const startEdit = (row) => {
  editingRow.value = row[props.rowKey]
  editingForm.value = { ...row }
}

// 取消编辑
const cancelEdit = () => {
  editingRow.value = null
  editingForm.value = {}
}

// 保存编辑
const saveEdit = () => {
  emit('row-edit', editingForm.value)
  editingRow.value = null
  editingForm.value = {}
}

// 删除行
const deleteRow = (row) => {
  emit('row-delete', row)
}

// 添加行
const showAddForm = () => {
  addFormVisible.value = true
  addForm.value = props.columns.reduce((acc, col) => {
    if (col.prop) {
      acc[col.prop] = ''
    }
    return acc
  }, {})
}

// 保存新行
const saveNewRow = () => {
  emit('row-add', addForm.value)
  addFormVisible.value = false
  addForm.value = {}
}

// 取消添加
const cancelAdd = () => {
  addFormVisible.value = false
  addForm.value = {}
}

// 当表格数据变化时，重置到第一页
watch(() => props.data, () => {
  currentPage.value = 1
}, { deep: true })

//业主详细信息表示
import { useRouter } from 'vue-router';
const router = useRouter();
const showData = (ownerId) => {
  router.push({
    name: 'fyyOwner', // 建议使用路由名称而不是路径
    params: { id: ownerId } // 传递业主ID作为参数
  });
};
</script>
<template>
  <div class="data-table-container">
    <!-- 表格工具栏 -->
    <div class="table-toolbar flex justify-between items-center mb-4">
      <div>
        <el-button v-if="editable" type="primary" @click="showAddForm">
          <el-icon><Plus /></el-icon> 添加
        </el-button>
      </div>
      
      <div>
        <!-- 列控制下拉菜单 -->
        <el-dropdown v-if="columnControl" @command="toggleColumnVisibility" trigger="click">
          <el-button>
            列显示 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="col in columns" 
                :key="col.prop"
                :command="col.prop"
              >
                <el-checkbox 
                  :modelValue="visibleColumns.includes(col.prop)"
                  @update:modelValue="() => {}"
                  @click.stop
                >
                  {{ col.label }}
                </el-checkbox>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <el-table
      :data="currentPageData"
      v-loading="loading"
      style="width: 100%"
      @sort-change="handleSortChange"
      border
    >
      <!-- 序号列 -->
      <el-table-column type="index" width="50" label="序号" />
      
      <!-- 数据列 -->
      <el-table-column 
        v-for="col in columns.filter(c => visibleColumns.includes(c.prop))"
        :key="col.prop"
        :prop="col.prop"
        :label="col.label"
        :width="col.width"
        :sortable="col.sortable"
        :formatter="col.formatter"
      >
        <template v-if="col.type === 'date'" #default="scope">
          {{ new Date(scope.row[col.prop]).toLocaleDateString() }}
        </template>
        
        <template v-else-if="col.type === 'status'" #default="scope">
          <el-tag :type="col.statusMap?.[scope.row[col.prop]]?.type || 'info'">
            {{ col.statusMap?.[scope.row[col.prop]]?.label || scope.row[col.prop] }}
          </el-tag>
        </template>
        
        <template v-else-if="col.type === 'custom'" #default="scope">
          <slot :name="`col-${col.prop}`" :row="scope.row" :index="scope.$index"></slot>
        </template>
        
        <template v-else #default="scope">
          <template v-if="editingRow === scope.row[rowKey] && col.editable !== false">
            <el-input v-model="editingForm[col.prop]" size="small" />
          </template>
          <span v-else>{{ scope.row[col.prop] }}</span>
        </template>
      </el-table-column>      
      <!-- 操作列 -->
      <el-table-column v-if="editable" label="操作" width="250" fixed="right">
        <template #default="scope">  
          <template v-if="editingRow === scope.row[rowKey]">
            <el-button type="primary" size="small" @click="saveEdit">保存</el-button>
            <el-button size="small" @click="cancelEdit">取消</el-button>
          </template>
          <template v-else>        
            <el-button 
              size="small"
              type="primary" 
              @click="startEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定删除该条记录吗？"
              @confirm="deleteRow(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div v-if="pagination && total > 0" class="pagination-container mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 添加表单对话框 -->
    <el-dialog
      v-model="addFormVisible"
      title="添加记录"
      width="30%"
    >
      <el-form :model="addForm" label-width="80px">
        <el-form-item 
          v-for="col in columns.filter(c => c.editable !== false)" 
          :key="col.prop"
          :label="col.label"
        >
          <el-input v-model="addForm[col.prop]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="saveNewRow">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.data-table-container {
  width: 100%;
}

.table-toolbar {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
}

/* 优化按钮样式 */
.el-table .cell {
  white-space: nowrap;
}

/* 确保所有按钮都有完整边框 */
.operation-buttons .el-button {
  border: 1px solid #e0e0e0 !important;
  margin-right: 4px; /* 增加按钮间距 */
}

/* 确保按钮组容器不影响边框 */
.operation-buttons {
  display: flex;
  gap: 4px;
  padding: 2px;
  box-sizing: border-box;
}

.operation-buttons el-button:last-child {
  margin-right: 0;
}
</style> 